"use strict";
/**
 * 响应往微信发送消息
 * Created by liamjung on 2018/6/28.
 */
const RunningModeEnum = require("@libfintech/api-gateway-core/enumeration/running_mode");
const {getMpConfig} = require("@libfintech/api-gateway-core/util/util");
const {getWechatApi} = require("@libfintech/api-gateway-core/util/wechat_api_util");
const {executeRest} = require("@libfintech/api-gateway-core/util/rest_util");

module.exports = async function (pipeline) {

    let body = pipeline.response.body;

    pipeline.logger.debug("wx response body: " + body);

    let data = JSON.parse(body);

    if (appConfig.runningMode === RunningModeEnum.CLUSTER && data.errcode === 40001) {

        let mpId = pipeline.ctx.request.body.mpId;
        let mpConfig = await getMpConfig(mpId);

        if (mpConfig) {
            //删除accessToken属性后，触发刷新，达到强制刷新目的
            delete mpConfig.accessToken;

            let wechatApi = await getWechatApi(mpConfig);

            wechatApi.logger = pipeline.logger;
            //强制刷新access token
            const {accessToken} = await wechatApi.ensureAccessToken();

            let req = pipeline.request;

            req.query = {
                access_token: accessToken
            };

            let [res, err] = await executeRest(req, pipeline.logger);

            if (res) {
                body = res.body;

                pipeline.logger.debug("wx response body for retry: " + body);

                data = JSON.parse(body);
            } else {
                Log.warn(err);
            }
        }
    }

    //ResultDTO
    let dto = {
        success: data.errcode === 0,
        errorMsg: data.errmsg,
        data: body
    };

    let resp = {
        status: pipeline.response.status,
        body: JSON.stringify(dto)
    };

    pipeline.response.update(resp);
};